package org.dev.biz_order.address

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.TextUtils
import android.view.*
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import kotlinx.android.synthetic.main.dialog_add_new_address.*
import org.dev.`as`.project.common.city.CityMgr
import org.dev.`as`.project.common.ui.view.showToast
import org.dev.biz_order.R
import org.dev.hi.hiui.cityselector.CitySelectorDialogFragment
import org.dev.hi.hiui.cityselector.Province
import org.dev.hi.library.util.HiRes

/**
 * Author WenPing
 * CreateTime 2021/9/4.
 * Description:
 */
class AddEditingDialogFragment : AppCompatDialogFragment() {

    private var onSavedAddressListener: OnSavedAddressListener? = null

    private var address: Address? = null
    private var selectProvince: Province? = null

    companion object {
        const val KEY_ADDRESS_PARAMS = "key_address"
        fun newInstance(address: Address?): AddEditingDialogFragment {
            val args = Bundle()
            args.putParcelable(KEY_ADDRESS_PARAMS, address)
            val fragment = AddEditingDialogFragment()
            fragment.arguments = args
            return fragment
        }
    }

    // 配置 api dependency.fragment_ktxactivity或者fragment的ktx拓展依赖，则可以简化写法
    private val viewModel by viewModels<AddressViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 获取携带过来的参数
        address = arguments?.getParcelable(KEY_ADDRESS_PARAMS)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val window = dialog?.window
        val root = window?.findViewById<ViewGroup>(R.id.content) ?: container

        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        window?.setLayout(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.WRAP_CONTENT
        )
        val contentView = inflater.inflate(
            R.layout.dialog_add_new_address, root, false
        )
        return contentView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 右侧 关闭按钮
        val closeBtn = nav_nar.addRightTextButton(
            R.string.if_close,
            R.id.nav_id_close
        )
        closeBtn.textSize = 25f
        // 关闭dialogFragment
        closeBtn.setOnClickListener { dismiss() }

        // 选择城市区域
        address_pick
            .getEditTextView()
            // 设置右侧的图标
            .setCompoundDrawablesWithIntrinsicBounds(
                0, 0, R.drawable.ic_right_arrow, 0
            )
        // 在不拉起软键盘的情况,响应点击事件,而不是用 isEnable = false
        address_pick.getEditTextView()
            .isFocusable = false
        address_pick.getEditTextView().isFocusableInTouchMode = false
        address_pick.getEditTextView().setOnClickListener {
            val liveData = CityMgr.getCityData()
            // 避免监听多个
            liveData.removeObservers(viewLifecycleOwner)
            liveData.observe(viewLifecycleOwner, Observer {
                // 拉起城市选择器
                if (it != null) {
                    val citySelector = CitySelectorDialogFragment.newInstance(selectProvince, it)
                    citySelector.setCitySelectListener(object :
                        CitySelectorDialogFragment.onCitySelectListener {
                        override fun onCitySelect(province: Province) {
                            updateAddressPick(province)
                        }
                    })
                    citySelector.show(childFragmentManager, "city_selector")
                } else {
                    showToast(HiRes.getString(R.string.city_data_set_empty))
                }
            })

        }

        // 详细地址
        address_detail.apply {
            getTitleView().gravity = Gravity.TOP
            getEditTextView().gravity = Gravity.TOP
            getEditTextView().isSingleLine = false
        }

        // 数据回填
        if (address != null) {
            user_name.getEditTextView().setText(address!!.receiver)
            user_phone.getEditTextView().setText(address!!.phoneNum)
            address_pick.getEditTextView()
                .setText("${address!!.province} ${address!!.city} ${address!!.area}")
            address_pick.getEditTextView().setText(address!!.detail)
        }

        action_save_address.setOnClickListener {
            // 保存地址
            savedAddress()
        }

    }

    private fun savedAddress() {
        val phone = user_phone.getEditTextView().text.toString().trim()
        val receiver = user_name.getEditTextView().text.toString().trim()
        val detail = address_detail.getEditTextView().text.toString().trim()
        val cityArea = address_pick.getEditTextView().text.toString().trim()

        // 对这四个值进行判空
        if (TextUtils.isEmpty(phone)
            || TextUtils.isEmpty(receiver)
            || TextUtils.isEmpty(detail)
            || TextUtils.isEmpty(cityArea)
        ) {
            showToast(HiRes.getString(R.string.address_info_too_simple))
            return
        }

        val province = selectProvince?.districtName ?: address?.province
        val city = selectProvince?.selectCity?.districtName ?: address?.city
        val district = selectProvince?.selectDistrict?.districtName ?: address?.area
        if (TextUtils.isEmpty(province) || TextUtils.isEmpty(city) || TextUtils.isEmpty(district)) {
            showToast(HiRes.getString(R.string.address_info_too_simple))
            return
        }
        if (address == null) {
            // 新增地址保存
            viewModel
                .saveAddress(province!!, city!!, district!!, detail, receiver, phone)
                .observe(viewLifecycleOwner, obsever)
        } else {
            // 更新地址
            viewModel.updateAddress(
                address!!.id,
                province!!,
                city!!,
                district!!,
                detail,
                receiver,
                phone
            ).observe(viewLifecycleOwner, obsever)
        }
    }

    /**
     * 更新选择的地区信息
     */
    private fun updateAddressPick(province: Province) {
        this.selectProvince = province
        address_pick.getEditTextView()
            .setText("${province.districtName} ${province.selectCity?.districtName} ${province.selectDistrict?.districtName}")

    }

    private val obsever = Observer<Address?> { address ->
        if (address != null) {
            // 回传结果
            onSavedAddressListener?.onSavedAddress(address)
            dismiss()
        }
    }


    fun setOnSavedAddressListener(listener: OnSavedAddressListener) {
        this.onSavedAddressListener = listener
    }

    interface OnSavedAddressListener {
        fun onSavedAddress(address: Address)
    }

}